#include <dbg.h>

#include <cassert>

using namespace std;

class Solution {
public:
    int longestEqualSubarray(vector<int>& nums, int k) {
        int n = nums.size();
        vector<vector<int>> pos(
            n + 1);  // 记录每个数字的构成最长等值数组的需要删除的元素个数
        for (int i = 0; i < n; ++i) {
            int x = nums[i];
            pos[x].push_back(i - pos[x].size());
        }
        dbg(pos);

        int res = 0;
        for (auto& p : pos) {
            int left = 0;
            for (int right = 0; right < p.size(); ++right) {
                while (p[right] - p[left] > k) {
                    ++left;
                }
                res = max(res, right - left + 1);
            }
        }
        return res;
    }
};

int main() {
    Solution s;

    vector<int> nums1 = {1, 3, 2, 3, 1, 3};
    vector<int> nums2 = {1, 1, 2, 2, 1, 1};

    int k1 = 3;
    int k2 = 2;

    assert(s.longestEqualSubarray(nums1, k1) == 3);
    // assert(s.longestEqualSubarray(nums2, k2) == 4);

    return 0;
}